package com.jxltech.unicam;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.jxltech.unicam.utils.AudioPlayer;
import com.jxltech.unicam.utils.Constants;
import com.jxltech.unicam.utils.DerbyDb;
import com.jxltech.unicam.utils.SerialPortManager;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

/**
 * MenuBar is part of the frame and handles all menu actions
 *
 * @author Jelmerro
 */
public class MenuBar extends JMenuBar {

	private SettingsDialog settingsDialog;
	private AboutDialog aboutDialog;

	/**
	 * Creates the MenuBar
	 */
	public MenuBar() {
		//Create and add the Menu
		JMenu menu = new JMenu("设置");
		add(menu);
		//Preferences item
		JMenuItem prefs = new JMenuItem("个性化");
		//To make sure the detect option works without going to the settings first,
		//already refresh the list of webcams
		settingsDialog = new SettingsDialog();
		settingsDialog.refreshWebcams();
		prefs.addActionListener(e -> {
			//When opening the settings, refresh the list of webcams
			settingsDialog.refreshWebcams();
			settingsDialog.show();
		});
		prefs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0));
		menu.add(prefs);
		//Detect resolution item
		JMenuItem maxres = new JMenuItem("照相机校准");
		maxres.addActionListener(e -> {
			maxres.setEnabled(false);
			//If a webcam is selected, try to set a resolution of 1000000x1000000
			//The api will automatically lower the resolution to a supported one
			//Also shows the LoadingDialog and displays a warning when no webcam is found
			if (settingsDialog.getLeftWebcam() != null) {
				Dimension dimension = new Dimension(10000, 10000);
				LoadingDialog loadingDialog = new LoadingDialog();
				loadingDialog.load(settingsDialog.getLeftWebcam(), settingsDialog.getRightWebcam(), dimension);
			} else {
				JOptionPane.showMessageDialog(null, "找不到可用的摄像头", "摄像头警告", JOptionPane.WARNING_MESSAGE);
			}
			enableItem(maxres);
		});
		maxres.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0));
		menu.add(maxres);

		//Snapshot item
		JMenuItem screenshot = new JMenuItem("拍照");
		screenshot.addActionListener(e -> {
			shot(screenshot);
		});
		screenshot.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0));
		menu.add(screenshot);
		//Mirror item
		JMenuItem mirror = new JMenuItem("镜像角度");
		mirror.addActionListener(e -> {
			mirror.setEnabled(false);
			//If exists mirror the panel
			if (Frame.getInstance().getLeftPanel() != null) {
				Frame.getInstance().getLeftPanel().setMirrored(!Frame.getInstance().getLeftPanel().isMirrored());
				Frame.getInstance().getRightPanel().setMirrored(!Frame.getInstance().getRightPanel().isMirrored());
			}
			enableItem(mirror);
		});
		mirror.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, 0));
		menu.add(mirror);
		//Copy item

		/**
		 * JMenuItem clipboard = new JMenuItem("Copy to clipboard");
		 * 		clipboard.addActionListener(e -> {
		 * 			clipboard.setEnabled(false);
		 * 			Frame.getInstance().imageToClipboard();
		 * 			enableItem(clipboard);
		 *                });
		 * 		clipboard.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, 0));
		 * 		menu.add(clipboard);
		 */

		//Fullscreen item
		JMenuItem fullscreen = new JMenuItem("全屏");
		fullscreen.addActionListener(e -> {
			fullscreen.setEnabled(false);
			Frame.getInstance().toggleFullscreen();
			enableItem(fullscreen);
		});
		fullscreen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, 0));
		menu.add(fullscreen);
		//About item
		JMenuItem about = new JMenuItem("关于");
		aboutDialog = new AboutDialog();
		about.addActionListener(e -> {
			aboutDialog.setVisible(true);
		});
		about.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0));
		menu.add(about);

		//Debug item
		JMenuItem debug = new JMenuItem(Constants.debug ? "关闭调试" : "打开调试");
		debug.addActionListener(e -> {
			Constants.debug = !Constants.debug;
			debug.setText(Constants.debug ? "关闭调试" : "打开调试");
		});

		menu.add(debug);

		//Exit item
		JMenuItem exit = new JMenuItem("退出");
		exit.addActionListener(e -> {
			Object[] options = {"确定", "取消"};
			int selectedValue = JOptionPane.showOptionDialog(Frame.getInstance(),
					"确定退出程序么？", "退出",
					JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
			if (selectedValue == 0)
				System.exit(0);
		});
		exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
		menu.add(exit);

		//
		initUi();
		SerialPortManager.setMenuBar(this);
	}

	private void shot(JMenuItem screenshot) {
		screenshot.setEnabled(false);
		//If a webcam is selected, try to save the image
		//Any exceptions will display an error message
		if (settingsDialog.getLeftWebcam() != null) {
			try {
				BufferedImage leftImage = settingsDialog.getLeftWebcam().getImage();
				BufferedImage rightImage = settingsDialog.getRightWebcam().getImage();
				if (leftImage != null && rightImage != null) {
					String date = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN);
					saveImgByDate(leftImage, Frame.getInstance().getLeftPanel(), date, "left.png");
					saveImgByDate(rightImage, Frame.getInstance().getRightPanel(), date, "right.png");
					//调试开关打开，弹出框
					if (Constants.debug) {
						Object[] options = {"合格", "不合格"};
						int selectedValue = JOptionPane.showOptionDialog(Frame.getInstance(),
								"清选择纸盒分类", "人工辅助",
								JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
						System.out.println(selectedValue);
						DerbyDb.insertImg(DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN) + "/" + date, selectedValue == 0);
					}else{
						callPredict();
						//声音输出
						outputMp3();
					}
				}
			} catch (Exception ex) {
				JOptionPane.showMessageDialog(null, "Failed to save image", "Save failure", JOptionPane.ERROR_MESSAGE);
			}
		}
		enableItem(screenshot);

	}

	private void callPredict() {
	}

	/**
	 * 当前积累数据，随机计算结果
	 */
	private void outputMp3() {
		if (RandomUtil.randomInt(2) == 0)
			AudioPlayer.pass();
		else
			AudioPlayer.fail();
	}

	private void saveImgByDate(BufferedImage image, ViewPanel viewPanel, String dateDir, String fileName) throws IOException {
		File imgFile = new File(fileName);
		ImageIO.write(image, "png", imgFile);
		FileUtil.move(imgFile,
				FileUtil.newFile(imgFile.getAbsoluteFile().getParent() + "/img/" +
						DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN) + "/" + dateDir + "/" + fileName),
				true);
		viewPanel.drawMessage("Saved screenshot: " + fileName);
	}

	public void shot() {
		shot(getMenu(0).getItem(2));
	}

	private void initUi() {
		if (settingsDialog.getLeftWebcam() != null && settingsDialog.getRightWebcam() != null) {
			Dimension dimension = new Dimension(10000, 10000);
			LoadingDialog loadingDialog = new LoadingDialog();
			loadingDialog.load(settingsDialog.getLeftWebcam(), settingsDialog.getRightWebcam(), dimension);
		} else {
			JOptionPane.showMessageDialog(null, "找不到可用的摄像头", "摄像头警告", JOptionPane.WARNING_MESSAGE);
		}
	}

	/**
	 * Getter for the SettingsDialog
	 *
	 * @return settingsDialog SettingsDialog
	 */
	public SettingsDialog getSettingsDialog() {
		return settingsDialog;
	}

	/**
	 * Re-enables a disabled item after 300mm to prevent spam
	 *
	 * @param item JMenuItem
	 */
	private void enableItem(JMenuItem item) {
		Timer t = new Timer();
		t.schedule(new TimerTask() {

			@Override
			public void run() {
				item.setEnabled(true);
			}
		}, 300);
	}
}
